<template>
  <div class="order-list-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>我的订单</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 筛选标签 -->
      <div class="filter-tabs">
        <el-radio-group v-model="statusFilter" @change="handleFilterChange">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="0">待付款</el-radio-button>
          <el-radio-button label="1">已付款</el-radio-button>
          <el-radio-button label="2">已发货</el-radio-button>
          <el-radio-button label="3">已收货</el-radio-button>
          <el-radio-button label="4">已评价</el-radio-button>
          <el-radio-button label="5">已取消</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>

      <!-- 订单列表 -->
      <div class="orders-content" v-loading="loading">
        <el-empty 
          v-if="!loading && orderList.length === 0" 
          description="暂无订单"
        >
          <el-button type="primary" @click="goToHome">去逛逛</el-button>
        </el-empty>

        <div v-else class="order-list">
          <div 
            v-for="order in orderList" 
            :key="order.id"
            class="order-item"
          >
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-id">订单号：{{ order.id }}</span>
                <span class="order-time">下单时间：{{ formatDateTime(order.createTime) }}</span>
              </div>
              <el-tag :type="getStatusTag(order.status)" size="large">
                {{ getStatusName(order.status) }}
              </el-tag>
            </div>

            <!-- 商品信息 -->
            <div class="order-goods">
              <!-- 单商品订单 -->
              <div v-if="order.goodsId" class="goods-item" @click="goToGoodsDetail(order.goodsId)">
                <img :src="getImageUrl(order.picture)" class="goods-image" />
                <div class="goods-info">
                  <h3 class="goods-name">{{ order.goodsName }}</h3>
                  <p class="goods-desc">{{ order.desc }}</p>
                  <div class="goods-meta">
                    <span class="goods-quantity">数量：{{ order.payNum }}</span>
                  </div>
                </div>
              </div>

              <!-- 多商品订单 -->
              <div v-else class="multi-goods">
                <div 
                  v-for="(goodsId, index) in parseGoodsIds(order.goodsIds)" 
                  :key="goodsId"
                  class="goods-item"
                  @click="goToGoodsDetail(goodsId)"
                >
                  <img :src="getImageUrl(parseGoodsPictures(order.pictures)[index])" class="goods-image" />
                  <div class="goods-info">
                    <h3 class="goods-name">{{ parseGoodsNames(order.goodsNames)[index] }}</h3>
                    <div class="goods-meta">
                      <span class="goods-quantity">数量：{{ parseGoodsNums(order.goodsNums)[index] }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 价格信息 -->
            <div class="price-info">
              <div v-if="order.discountAmount > 0" class="discount-info">
                <span class="original-price">原价：¥{{ order.originalPrice }}</span>
                <span class="discount-amount">优惠：-¥{{ order.discountAmount }}</span>
              </div>
              <div class="final-price">
                实付：<span class="price-value">¥{{ order.price }}</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="order-actions">
              <el-button 
                v-if="order.status === 0" 
                type="primary"
                @click="handlePay(order)"
              >
                立即支付
              </el-button>
              
              <el-button 
                v-if="order.status === 0" 
                type="info"
                @click="handleCancel(order)"
              >
                取消订单
              </el-button>

              <el-button 
                v-if="order.status === 2" 
                type="success"
                @click="handleConfirmReceive(order)"
              >
                确认收货
              </el-button>

              <el-button 
                v-if="order.status === 3 && !order.commentId" 
                type="warning"
                @click="handleComment(order)"
              >
                评价商品
              </el-button>

              <el-button 
                v-if="[1, 2, 3].includes(order.status)" 
                type="danger"
                plain
                @click="handleRefund(order)"
              >
                申请退款
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          class="pagination"
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="loadOrders"
          @current-change="loadOrders"
        />
      </div>
    </div>

    <!-- 支付对话框 -->
    <PaymentDialog 
      v-model="showPaymentDialog" 
      :order="selectedOrder"
      @success="handlePaymentSuccess"
    />

    <!-- 评价对话框 -->
    <CommentDialog 
      v-model="showCommentDialog" 
      :order="selectedOrder"
      @success="handleCommentSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getMyOrders, updateOrder } from '@/api/order'
import { getFileUrl } from '@/api/file'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'
import PaymentDialog from '@/components/PaymentDialog.vue'
import CommentDialog from '@/components/CommentDialog.vue'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const orderList = ref([])
const statusFilter = ref('')
const searchKeyword = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const showPaymentDialog = ref(false)
const showCommentDialog = ref(false)
const selectedOrder = ref(null)

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    const data = await getMyOrders({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      status: statusFilter.value || undefined,
      goodsName: searchKeyword.value || undefined
    })
    orderList.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取订单失败:', error)
  } finally {
    loading.value = false
  }
}

// 筛选变化
const handleFilterChange = () => {
  pageNum.value = 1
  loadOrders()
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1
  loadOrders()
}

// 解析多商品ID
const parseGoodsIds = (goodsIds) => {
  return goodsIds ? goodsIds.split(';').map(id => parseInt(id)) : []
}

// 解析多商品名称
const parseGoodsNames = (goodsNames) => {
  return goodsNames ? goodsNames.split(';') : []
}

// 解析多商品图片
const parseGoodsPictures = (pictures) => {
  return pictures ? pictures.split(';') : []
}

// 解析多商品数量
const parseGoodsNums = (goodsNums) => {
  return goodsNums ? goodsNums.split(';').map(num => parseInt(num)) : []
}

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    0: '待付款',
    1: '已付款',
    2: '已发货',
    3: '已收货',
    4: '已评价',
    5: '已取消',
    6: '退单中',
    7: '已退单',
    8: '拒绝退单'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签
const getStatusTag = (status) => {
  const tagMap = {
    0: 'warning',
    1: 'success',
    2: 'primary',
    3: 'success',
    4: 'info',
    5: 'info',
    6: 'warning',
    7: 'success',
    8: 'danger'
  }
  return tagMap[status] || 'info'
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}

// 格式化日期时间
const formatDateTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 支付
const handlePay = (order) => {
  selectedOrder.value = order
  showPaymentDialog.value = true
}

// 支付成功
const handlePaymentSuccess = () => {
  ElMessage.success('支付成功')
  loadOrders()
}

// 取消订单
const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await updateOrder({
      orderId: order.id,
      orderStatus: 5
    })
    
    ElMessage.success('订单已取消')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
    }
  }
}

// 确认收货
const handleConfirmReceive = async (order) => {
  try {
    await ElMessageBox.confirm('确定已收到商品吗？', '确认收货', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await updateOrder({
      orderId: order.id,
      orderStatus: 3
    })
    
    ElMessage.success('确认收货成功')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
    }
  }
}

// 评价商品
const handleComment = (order) => {
  selectedOrder.value = order
  showCommentDialog.value = true
}

// 评价成功
const handleCommentSuccess = () => {
  ElMessage.success('评价成功')
  loadOrders()
}

// 申请退款
const handleRefund = async (order) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入退款理由', '申请退款', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入退款理由',
      inputValidator: (value) => {
        if (!value || value.trim().length === 0) {
          return '请输入退款理由'
        }
        return true
      }
    })

    await updateOrder({
      orderId: order.id,
      orderStatus: 6,
      reason: reason
    })
    
    ElMessage.success('退款申请已提交')
    loadOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('申请退款失败:', error)
    }
  }
}

// 跳转到商品详情
const goToGoodsDetail = (goodsId) => {
  router.push(`/goods/${goodsId}`)
}

// 回到首页
const goToHome = () => {
  router.push('/')
}

onMounted(() => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  loadOrders()
})
</script>

<style scoped>
.order-list-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.filter-tabs {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-box {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.orders-content {
  min-height: 400px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

.order-item {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-id {
  font-weight: 500;
  color: #333;
}

.order-time {
  color: #999;
  font-size: 14px;
}

.order-goods {
  margin-bottom: 20px;
}

.multi-goods {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.goods-item {
  display: flex;
  gap: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.goods-item:hover {
  background-color: #f9f9f9;
}

.goods-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.goods-desc {
  font-size: 14px;
  color: #999;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-meta {
  display: flex;
  gap: 15px;
}

.goods-quantity {
  font-size: 14px;
  color: #666;
}

.price-info {
  text-align: right;
  margin-bottom: 20px;
}

.discount-info {
  margin-bottom: 5px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-right: 10px;
}

.discount-amount {
  font-size: 14px;
  color: #ff4d4f;
}

.final-price {
  font-size: 16px;
  color: #333;
}

.price-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .order-info {
    flex-direction: column;
    gap: 5px;
  }

  .goods-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .goods-image {
    width: 60px;
    height: 60px;
  }

  .price-info {
    text-align: left;
  }

  .order-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}
</style>
